package cn.cw.myupdatedemo;

import android.app.Dialog;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Build;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;

import cn.cw.myupdatedemo.download.CommonDialog;
import cn.cw.myupdatedemo.download.DownLoadBuilder;
import cn.cw.myupdatedemo.download.bean.UpdateResultBean;
import cn.cw.myupdatedemo.okhttp.BaseCallBack;
import cn.cw.myupdatedemo.okhttp.OkUtil;
import okhttp3.Call;

/**
 * @author zzj15_hqeovpj
 */
public class SecondActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        downloadCompleteBroadcast = new DownloadCompleteBroadcast();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        registerReceiver(downloadCompleteBroadcast,intentFilter);
        checkNewVersion();
    }


    private String mUpdateUrl = "http://172.22.7.230:8085/patch/patch/version?";
    private String mDownloadUrl = "http://172.22.7.230:8085/patch/patch/download?termid=";
    private String mTeamId= "sanmingLibrary";

    private DownloadCompleteBroadcast downloadCompleteBroadcast;
    private CommonDialog commonDialog;
    private String apkName = "测试";

    private void checkNewVersion(){
        OkUtil.newBuilder()
                .addParam("termid", mTeamId)
                .get()
                .url(mUpdateUrl)
                .build()
                .enqueue(new BaseCallBack<UpdateResultBean>() {

                    @Override
                    public void onSuccess(UpdateResultBean updateResultBean) {
                        String tip = "";
                        if (updateResultBean.getVersionCode() == null&&updateResultBean.getPatchNumber() == null) {
                            Toast.makeText(SecondActivity.this, "已经是最新版本", Toast.LENGTH_LONG).show();
                        } else {
                            int localVersion = Integer.parseInt(getVersionCode(SecondActivity.this));
                            Log.e("result", "localVersion" + localVersion);
                            if ( localVersion< Integer.parseInt(updateResultBean.getVersionCode())) {
                                final String url = mDownloadUrl + mTeamId + "&filename=" + updateResultBean.getFilename();
                                apkName = updateResultBean.getFilename();
                                Log.e("result", "url:" + url);
                                final String description = updateResultBean.getPatchNote();
                                commonDialog = new CommonDialog.Builder(SecondActivity.this)
                                        .view(R.layout.dialog)
                                        .style(R.style.Dialog)
                                        .setMessage(R.id.txt_sure, "开始更新")
                                        .setMessage(R.id.txt_cancel, "取消更新")
                                        .setMessage(R.id.txt_content, description)
                                        .addViewOnClick(R.id.txt_sure, new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                new DownLoadBuilder.Builder(SecondActivity.this)
                                                        .addUrl(url)
                                                        .isWiFi(true)
                                                        .addDownLoadName(apkName)
                                                        .addDscription(description)
                                                        .builder();
                                                Toast.makeText(SecondActivity.this, "开始下载", Toast.LENGTH_SHORT).show();
                                                commonDialog.dismiss();
                                            }
                                        })
                                        .addViewOnClick(R.id.txt_cancel, new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                commonDialog.dismiss();
                                            }
                                        })
                                        .build();

                                commonDialog.show();

                            } else {
                                Toast.makeText(SecondActivity.this, "已经是最新版本", Toast.LENGTH_LONG).show();
                            }
                        }


                    }

                    @Override
                    public void onError(int code) {

                    }

                    @Override
                    public void onFailure(Call call, IOException e) {

                    }
                });
    }

    private String getVersionCode(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            return String.valueOf(packageInfo.versionCode);

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(downloadCompleteBroadcast);
    }


    class DownloadCompleteBroadcast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)){
                /*
                 * 获取下载完成对应的下载ID, 这里下载完成指的不是下载成功, 下载失败也算是下载完成,
                 * 所以接收到下载完成广播后, 还需要根据 id 手动查询对应下载请求的成功与失败.
                 */
                long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1L);
                // 根据获取到的ID，使用上面第3步的方法查询是否下载成功
                DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(downloadId);
                Cursor cursor = manager.query(query);
                if (!cursor.moveToFirst()) {
                    cursor.close();
                    return;
                }
                int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
                String localFilename;
                if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){
                    localFilename = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                }else{
                    localFilename = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
                }
                if (status == DownloadManager.STATUS_SUCCESSFUL) {
                    Log.e("down","下载成功, 打开文件, 文件路径: " + localFilename);
//                setPermission(localFilename);
//                DownLoadBuilder.intallApk(SecondActivity.this,apkName);

                File fileTest = new File(Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DOWNLOADS, apkName+ ".apk");
                DownLoadBuilder.silentInstall(fileTest.getPath());
                }
            }
        }
    }

}
